<template>
  <div class="app-container">
    <el-form size="small" inline>
      <el-form-item label="所属地区">
        <agriculture-region :value.sync="query.deptId" ref="agricultureRegion" />
      </el-form-item>
      <el-form-item label="土地编码">
        <el-input placeholder="请输入土地编码" clearable v-model="query.landCode" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>
        <el-button plain icon="el-icon-plus" type="success" @click="addDialogVisible = true">新增</el-button>
        <el-button plain icon="el-icon-download" type="warning" @click="handleExport">导出</el-button>
        <!--				<el-button plain icon="el-icon-upload2" type="danger" @click="uploadDialogVisible = true">导入</el-button>-->
        <help></help>
      </el-form-item>
    </el-form>
    <el-table border v-loading="loading" :data="list">
      <el-table-column align="center" label="土地编码/地宗号" prop="landCode" min-width="120" show-overflow-tooltip />
      <el-table-column
        align="center"
        label="土地证书号"
        prop="landCertificateNumber"
        min-width="110"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="图号" prop="pictureNumber" min-width="100" show-overflow-tooltip />
      <el-table-column align="center" label="所属地区" prop="deptId" min-width="110" show-overflow-tooltip>
        <template slot-scope="scope">
          <agriculture-region :value.sync="scope.row.deptId" type="text" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="宗地面积" prop="area" min-width="100" show-overflow-tooltip />
      <el-table-column align="center" label="用途" min-width="80">
        <template slot-scope="scope">
          <dict-tag :option="dict.type.land_use" :value="scope.row.useRange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="110">
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-document" @click="landDetail(scope.row)">详情</el-button>
          <el-button type="text" size="small" icon="el-icon-edit" @click="updateLandDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="deleteLand(scope.row.landId)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />
    <help-dialog :title="title" :visible.sync="addDialogVisible" @close="addClose">
      <el-form size="small" label-width="130px" :model="queryParam" :rules="rules" ref="form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="土地编码/地宗号" prop="landCode">
              <el-input v-model="queryParam.landCode" placeholder="请输入土地编码/地宗号" clearable />
            </el-form-item>
            <el-form-item label="图号" prop="pictureNumber">
              <el-input v-model="queryParam.pictureNumber" placeholder="请输入图号" clearable />
            </el-form-item>
            <el-form-item label="面积" prop="area">
              <el-input v-model="queryParam.area" placeholder="请输入面积" clearable />
            </el-form-item>
            <el-form-item label="所属地区" prop="deptId">
              <agriculture-region :value.sync="queryParam.deptId" />
            </el-form-item>
            <el-form-item label="坐标（东至）" prop="east">
              <el-input v-model="queryParam.east" placeholder="请输入坐标（东至）" />
            </el-form-item>
            <el-form-item label="坐标（西至）" prop="west">
              <el-input v-model="queryParam.west" placeholder="请输入坐标（西至）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="土地证书号" prop="landCertificateNumber">
              <el-input v-model="queryParam.landCertificateNumber" placeholder="请输入土地证书号" clearable />
            </el-form-item>
            <el-form-item label="是否基本农田" prop="basicLand">
              <el-select v-model="queryParam.basicLand" placeholder="请选择是否基本农田" clearable style="width: 100%">
                <el-option
                  v-for="item in dict.type.agriculture_basic_land"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用途" prop="useRange">
              <el-select v-model="queryParam.useRange" placeholder="请选择用途" clearable>
                <el-option
                  v-for="item in dict.type.land_use"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="queryParam.address" type="textarea" :rows="2" placeholder="县（市，区）路号" />
            </el-form-item>
            <el-form-item label="坐标（南至）" prop="south">
              <el-input v-model="queryParam.south" placeholder="请输入坐标（南至）" />
            </el-form-item>
            <el-form-item label="坐标（北至）" prop="north">
              <el-input v-model="queryParam.north" placeholder="请输入坐标（北至）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="经纬度" prop="locateAddress">
          <div>
            <el-amap-search-box
              class="search-box"
              :search-option="searchOption"
              :on-search-result="onSearchResult"
            ></el-amap-search-box>
            <el-amap
              vid="amapDemo"
              :center="[queryParam.lng, queryParam.lat]"
              :amap-manager="aMapManager"
              :zoom="zoom"
              :events="events"
              class="amap-demo"
              style="height: 300px"
            >
              <el-amap-marker
                ref="marker"
                vid="component-marker"
                :position="[queryParam.lng, queryParam.lat]"
              ></el-amap-marker>
            </el-amap>
            <p>标记点：{{ queryParam.locateAddress }}，经度：{{ queryParam.lng }}，纬度：{{ queryParam.lat }}</p>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addClose">取 消</el-button>
        <el-button v-if="queryParam.landId" type="primary" @click="updateLand">修 改</el-button>
        <el-button v-else type="primary" @click="addLand">确 定</el-button>
      </div>
    </help-dialog>

    <help-dialog title="土地详情" :visible.sync="infoDialogVisible">
      <el-descriptions title="土地基本信息">
        <el-descriptions-item label="土地编码/地宗号">{{ info.landCode }}</el-descriptions-item>
        <el-descriptions-item label="土地证书号">{{ info.landCertificateNumber }}</el-descriptions-item>
        <el-descriptions-item label="图号">{{ info.pictureNumber }}</el-descriptions-item>
        <el-descriptions-item label="是否基本农田">
          <dict-tag :options="dict.type.agriculture_basic_land" :value="info.basicLand" />
        </el-descriptions-item>
        <el-descriptions-item label="面积">{{ info.area }}</el-descriptions-item>
        <el-descriptions-item label="用途">
          <dict-tag :option="dict.type.land_use" :value="info.useRange" />
        </el-descriptions-item>
        <el-descriptions-item label="所属地区">
          <agriculture-region :value.sync="info.deptId" type="text" />
        </el-descriptions-item>
        <el-descriptions-item label="坐标（四至）"
          >东至{{ info.east }}西至{{ info.west }}南至{{ info.south }}北至{{ info.north }}
        </el-descriptions-item>
        <el-descriptions-item label="经纬度">{{ info.gps }} {{ info.locateAddress }}</el-descriptions-item>
        <el-descriptions-item label="所属组织">
          <dict-tag :options="dict.type.agriculture_organization" :value="info.deptId" />
        </el-descriptions-item>
      </el-descriptions>
      <div class="label">经营数据</div>
      <el-descriptions
        v-for="(item, index) in info.contractorlist"
        :key="item.contractorId"
        :title="`承包户${index + 1}`"
      >
        <el-descriptions-item label="承包方代表">{{ item.contractorDeputy }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ item.idcardNumber }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ item.cellPhone }}</el-descriptions-item>
        <el-descriptions-item label="承包方式">{{ item.contractorType }}</el-descriptions-item>
        <el-descriptions-item label="合同代码"></el-descriptions-item>
        <el-descriptions-item label="承包期限">{{ item.deadline }}</el-descriptions-item>
        <el-descriptions-item label="权证附件">
          <y-show-all-file height="50px" width="50px" :path="item.file" />
        </el-descriptions-item>
        <el-descriptions-item label="所属组织">
          <dict-tag :options="dict.type.agriculture_organization" :value="item.deptId" />
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        v-for="(item, index) in info.personlist"
        :key="item.personManageId"
        :title="`个人经营户${index + 1}`"
      >
        <el-descriptions-item label="经营者姓名">{{ item.name }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ item.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ item.idcardNumber }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ item.address }}</el-descriptions-item>
        <el-descriptions-item label="流转期限"></el-descriptions-item>
        <el-descriptions-item label="流转合同附件">
          <y-show-all-file height="50px" width="50px" :path="item.contractFile" />
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        v-for="(item, index) in info.corplist"
        :key="item.corpManageId"
        :title="`企业经营户${index + 1}`"
      >
        <el-descriptions-item label="统一社会信用代码">{{ item.corpCode }}</el-descriptions-item>
        <el-descriptions-item label="企业名称">{{ item.name }}</el-descriptions-item>
        <el-descriptions-item label="企业类型">{{ item.corpType }}</el-descriptions-item>
        <el-descriptions-item label="法人/负责人姓名"> {{ item.legalMan }}</el-descriptions-item>
        <el-descriptions-item label="法人/负责人证件号码">{{ item.legalManIdcard }}</el-descriptions-item>
        <el-descriptions-item label="联络人姓名">{{ item.linkMan }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ item.linkPhone }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ item.address }}</el-descriptions-item>
        <el-descriptions-item label="流转方式">
          <dict-tag :options="dict.type.circulation_type" :value="item.circulationType" />
        </el-descriptions-item>
        <el-descriptions-item label="流转期限">{{ item.manageTime }}</el-descriptions-item>
        <el-descriptions-item label="流转合同附件">
          <y-show-all-file height="50px" width="50px" :path="item.contractFile" />
        </el-descriptions-item>
      </el-descriptions>
    </help-dialog>
    <help-dialog
      title="农地管理导入"
      :visible.sync="uploadDialogVisible"
      width="30%"
      align="center"
      @close="closeUpload"
    >
      <el-upload class="upload-demo" drag action="#" :http-request="imported" multiple ref="upload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过500kb</div>
      </el-upload>
      <el-button type="text" @click="templateDownload">土地管理导入模版</el-button>
    </help-dialog>
  </div>
</template>

<script>
import landApi from '@/api/land/land'
import AgricultureRegion from '@/components/AgricultureRegion/AgricultureRegion'
import { AMapManager } from 'vue-amap'

const aMapManager = new AMapManager()

export default {
  dicts: ['agriculture_basic_land', 'agriculture_organization', 'circulation_type', 'land_use'],
  components: { AgricultureRegion },
  data() {
    return {
      loading: false,
      list: [],
      addDialogVisible: false,
      infoDialogVisible: false,
      uploadDialogVisible: false,
      query: {
        pageNum: 1,
        pageSize: 10,
        landCode: ''
      },
      total: 0,
      title: '土地添加',
      queryParam: {
        landCode: '',
        pictureNumber: '',
        area: '',
        landCertificateNumber: '',
        useRange: '0',
        basicLand: '1',
        deptId: '',
        address: '',
        east: '',
        south: '',
        west: '',
        north: '',
        lng: 116.397451,
        lat: 39.909187,
        locateAddress: '北京市东城区东华门街道天安门'
      },
      value: '355,356',
      searchOption: {
        citylimit: false // 是否限制城市内搜索
      },
      aMapManager,
      zoom: 15,
      events: {
        click: (e) => {
          this.queryParam.lng = e.lnglat.lng
          this.queryParam.lat = e.lnglat.lat
          AMap.plugin('AMap.Geocoder', () => {
            let GeocoderOptions = { city: '全国' }
            let geocoder = new AMap.Geocoder(GeocoderOptions)
            geocoder.getAddress([this.queryParam.lng, this.queryParam.lat], (status, result) => {
              console.log('通过经纬度拿到的地址', result)
              if (status === 'complete' && result.info === 'OK') {
                this.queryParam.locateAddress = result.regeocode.formattedAddress
              } else {
                this.queryParam.locateAddress = '无法获取地址'
              }
            })
          })
        }
      },
      rules: {
        landCode: [{ required: true, message: '请输入土地编码/地宗号', trigger: 'blur' }],
        area: [{ required: true, message: '请输入面积', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择所属地区', trigger: 'blur' }]
      },
      info: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      landApi.landListData(this.query).then((res) => {
        this.list = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleReset() {
      this.query = {
        pageNum: 1,
        pageSize: 10,
        landCode: ''
      }
      this.getList()
    },
    handleExport() {
      this.download(
        '/agriculture/land/export',
        {
          deptId: this.query.deptId,
          landCode: this.query.landCode,
          remark: this.$refs.agricultureRegion.name
        },
        `农地管理_${new Date().getTime()}.xlsx`
      )
    },
    imported(item) {
      var formData = new FormData()
      formData.append('file', item.file)
      landApi.importLandData(formData).then((res) => {
        this.$message.success('导入成功')
        this.closeUpload()
        this.getList()
      })
    },
    closeUpload() {
      this.$refs.upload.clearFiles()
      this.uploadDialogVisible = false
    },
    addClose() {
      this.queryParam = {
        landCode: '',
        pictureNumber: '',
        area: '',
        landCertificateNumber: '',
        useRange: '0',
        basicLand: '1',
        deptId: '',
        address: '',
        east: '',
        south: '',
        west: '',
        north: '',
        gps: '',
        lng: 116.397451,
        lat: 39.909187,
        locateAddress: '北京市东城区东华门街道天安门'
      }
      this.addDialogVisible = false
      this.title = '土地添加'
    },
    onSearchResult(pois) {
      if (pois && pois.length) {
        const [data] = pois
        const { lng, lat, name, address } = data
        this.zoom = 18
        this.queryParam.lng = lng
        this.queryParam.lat = lat
      }
    },
    addLand() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.queryParam.gps = `${this.queryParam.lng},${this.queryParam.lat}`
          landApi.addLandData(this.queryParam).then((res) => {
            this.$message.success('添加成功')
            this.addClose()
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    deleteLand(landId) {
      this.$confirm('确定删除当前土地?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          landApi.deleteLandData({ landId: landId }).then((res) => {
            this.$message.success('删除成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    updateLandDialog(row) {
      let arr = []
      row.gps ? (arr = row.gps.split(',')) : (arr = ['116.397451', '39.909187'])
      row.lng = Number(arr[0])
      row.lat = Number(arr[1])

      AMap.plugin('AMap.Geocoder', () => {
        let GeocoderOptions = { city: '全国' }
        let geocoder = new AMap.Geocoder(GeocoderOptions)
        geocoder.getAddress(arr, (status, result) => {
          console.log('通过经纬度拿到的地址', result)
          if (status === 'complete' && result.info === 'OK') {
            row.locateAddress = result.regeocode.formattedAddress
          } else {
            row.locateAddress = '无法获取地址'
          }
          this.queryParam = { ...row }
          this.title = '土地更新'
          this.addDialogVisible = true
        })
      })
    },
    updateLand() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.queryParam.gps = `${this.queryParam.lng},${this.queryParam.lat}`
          landApi.updateLand(this.queryParam).then((res) => {
            this.$message.success('修改成功')
            this.addClose()
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    landDetail(row) {
      landApi.detailLand({ landId: row.landId }).then((res) => {
        let arr = []
        row.gps ? (arr = row.gps.split(',')) : (arr = ['116.397451', '39.909187'])
        row.lng = Number(arr[0])
        row.lat = Number(arr[1])

        AMap.plugin('AMap.Geocoder', () => {
          let GeocoderOptions = { city: '全国' }
          let geocoder = new AMap.Geocoder(GeocoderOptions)
          geocoder.getAddress(arr, (status, result) => {
            console.log('通过经纬度拿到的地址', result)
            if (status === 'complete' && result.info === 'OK') {
              res.data.locateAddress = result.regeocode.formattedAddress
            } else {
              res.data.locateAddress = '无法获取地址'
            }
            this.info = res.data
            this.infoDialogVisible = true
          })
        })
      })
    },
    templateDownload() {
      download('/profile/upload/2023/4/14/农地模板_98811240319347adb6dbbd513d89351b.xlsx')
    }
  }
}
</script>

<style scoped>
.label {
  font-size: 20px;
  font-weight: 700;
  color: #409eff;
  margin: 20px 0;
  border-left: 3px solid;
  padding-left: 5px;
  line-height: 20px;
}

/deep/ .el-descriptions__body .el-descriptions__table {
  white-space: nowrap;
}

/deep/ .el-descriptions-item__content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 8px;
}
</style>
